<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件总线测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 50px auto;
            padding: 20px;
        }
        .test-section {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 4px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        .event-log {
            background-color: #f0f0f0;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
            font-family: monospace;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <h1>🔧 事件总线通信测试</h1>
    
    <div class="test-section">
        <h3>模拟事件总线</h3>
        <p>这个页面模拟了Vue组件中的事件总线通信，帮助诊断问题：</p>
        
        <button onclick="testUserMessage()">测试用户消息事件</button>
        <button onclick="testAiChunk()">测试AI消息片段</button>
        <button onclick="testAiComplete()">测试AI响应完成</button>
        <button onclick="testAiError()">测试AI响应错误</button>
        <button onclick="clearLog()">清空日志</button>
        
        <div id="eventResult" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>模拟聊天历史组件</h3>
        <p>模拟ChatHistory组件的事件监听逻辑：</p>
        
        <div id="chatList" class="event-log">
            <div>聊天列表：[]</div>
        </div>
        
        <div id="aiStatus" class="event-log">
            <div>AI状态：未响应</div>
            <div>当前AI索引：-1</div>
        </div>
    </div>

    <script>
        // 模拟事件总线
        const eventBus = {
            listeners: {},
            on(event, callback) {
                if (!this.listeners[event]) {
                    this.listeners[event] = []
                }
                this.listeners[event].push(callback)
                console.log(`📡 注册事件监听器: ${event}`)
            },
            emit(event, data) {
                console.log(`📤 发送事件: ${event}`, data)
                if (this.listeners[event]) {
                    this.listeners[event].forEach(callback => {
                        try {
                            callback(data)
                        } catch (error) {
                            console.error(`❌ 事件处理错误 ${event}:`, error)
                        }
                    })
                } else {
                    console.warn(`⚠️ 没有监听器处理事件: ${event}`)
                }
            },
            off(event, callback) {
                if (this.listeners[event]) {
                    if (callback) {
                        const index = this.listeners[event].indexOf(callback)
                        if (index > -1) {
                            this.listeners[event].splice(index, 1)
                        }
                    } else {
                        delete this.listeners[event]
                    }
                }
            }
        }

        // 模拟聊天历史组件状态
        let chatList = []
        let isAiResponding = false
        let currentAiIndex = -1

        // 更新显示
        function updateDisplay() {
            document.getElementById('chatList').innerHTML = `
                <div>聊天列表：${JSON.stringify(chatList, null, 2)}</div>
            `
            document.getElementById('aiStatus').innerHTML = `
                <div>AI状态：${isAiResponding ? '响应中' : '未响应'}</div>
                <div>当前AI索引：${currentAiIndex}</div>
            `
        }

        // 模拟ChatHistory组件的事件监听
        function setupChatHistory() {
            // 新增用户消息
            eventBus.on('add-user-message', (userMsg) => {
                console.log('👤 收到用户消息事件:', userMsg)
                
                chatList.push({
                    role: 'user',
                    content: userMsg.content,
                    timestamp: userMsg.timestamp,
                    meta: null,
                    isLoading: false
                })

                // 初始化AI消息
                isAiResponding = true
                currentAiIndex = chatList.length
                chatList.push({
                    role: 'ai',
                    content: '',
                    timestamp: userMsg.timestamp,
                    meta: null,
                    isLoading: true
                })
                
                console.log('📝 当前聊天列表:', chatList)
                updateDisplay()
            })

            // 新增AI流式片段
            eventBus.on('add-ai-message-chunk', (chunk) => {
                console.log('🤖 收到AI消息片段:', chunk, '当前索引:', currentAiIndex)
                
                if (currentAiIndex >= 0 && currentAiIndex < chatList.length) {
                    chatList[currentAiIndex].content += chunk
                    console.log('📝 更新AI消息内容:', chatList[currentAiIndex].content)
                } else {
                    console.warn('⚠️ AI消息索引无效:', currentAiIndex, '聊天列表长度:', chatList.length)
                }
                updateDisplay()
            })

            // AI响应完成
            eventBus.on('ai-response-complete', (meta) => {
                console.log('✅ AI响应完成事件:', meta)
                
                isAiResponding = false
                if (currentAiIndex >= 0 && currentAiIndex < chatList.length) {
                    chatList[currentAiIndex].isLoading = false
                    chatList[currentAiIndex].meta = meta
                    console.log('📝 完成AI消息:', chatList[currentAiIndex])
                }
                updateDisplay()
            })

            // AI响应错误
            eventBus.on('ai-response-error', (errorMsg) => {
                console.log('❌ AI响应错误事件:', errorMsg)
                
                isAiResponding = false
                if (currentAiIndex >= 0 && currentAiIndex < chatList.length) {
                    chatList[currentAiIndex].content = `推荐失败：${errorMsg}`
                    chatList[currentAiIndex].isLoading = false
                }
                updateDisplay()
            })

            // 清空历史
            eventBus.on('clear-history', () => {
                console.log('🗑️ 清空历史事件')
                
                chatList = []
                isAiResponding = false
                currentAiIndex = -1
                updateDisplay()
            })
        }

        // 测试函数
        function testUserMessage() {
            const userMsg = {
                content: '我是小明',
                timestamp: new Date().toLocaleString(),
                username: '小明'
            }
            eventBus.emit('add-user-message', userMsg)
            logResult('✅ 发送用户消息事件成功', userMsg)
        }

        function testAiChunk() {
            const chunk = '根据您的需求，我为您推荐以下职场穿搭：'
            eventBus.emit('add-ai-message-chunk', chunk)
            logResult('✅ 发送AI消息片段成功', chunk)
        }

        function testAiComplete() {
            const meta = { prompt_tokens: 100, completion_tokens: 200 }
            eventBus.emit('ai-response-complete', meta)
            logResult('✅ 发送AI响应完成事件成功', meta)
        }

        function testAiError() {
            const errorMsg = '网络连接失败'
            eventBus.emit('ai-response-error', errorMsg)
            logResult('✅ 发送AI响应错误事件成功', errorMsg)
        }

        function clearLog() {
            document.getElementById('eventResult').innerHTML = ''
            chatList = []
            isAiResponding = false
            currentAiIndex = -1
            updateDisplay()
        }

        function logResult(message, data) {
            const resultDiv = document.getElementById('eventResult')
            const timestamp = new Date().toLocaleTimeString()
            resultDiv.innerHTML += `[${timestamp}] ${message}\n${JSON.stringify(data, null, 2)}\n\n`
            resultDiv.scrollTop = resultDiv.scrollHeight
        }

        // 初始化
        setupChatHistory()
        updateDisplay()
        
        console.log('🚀 事件总线测试页面已加载')
        console.log('💡 请点击按钮测试各种事件，观察控制台和页面变化')
    </script>
</body>
</html>
